package com.hexiang.data.split.aspectj;

import com.baomidou.mybatisplus.core.toolkit.ReflectionKit;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.hexiang.data.split.annotation.DataSplitTag;
import com.hexiang.data.split.enums.DataSplitEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.hint.HintManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Slf4j
@Aspect
@Component
public class DataSplitAspectj {

    @Pointcut("execution(public * com.*.service..*Service.*(..))")
    public void pointcut() {
    }

    @Pointcut("@target(com.hexiang.data.split.annotation.DataSplitTag)")
    public void annotation() {
    }

    @Around("pointcut()&&annotation()")
    public Object doDataSplit(ProceedingJoinPoint joinPoint) throws Throwable {

        Class<?> sourceClass = joinPoint.getTarget().getClass();
        //获取方法签名信息,方法名和参数列表
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        //获取目标方法对象
        Method method = sourceClass.getMethod(signature.getName(), signature.getParameterTypes());
        Class clazz = ReflectionKit.getSuperClassGenericType(sourceClass, 1);
        String tableName = SqlHelper.table(clazz).getTableName();
        HintManager.clear();
        HintManager hintManager = HintManager.getInstance();
        DataSplitTag dataSplitTagAnnotation = method.getAnnotation(DataSplitTag.class);
        if (null == dataSplitTagAnnotation) {
            hintManager.addTableShardingValue(tableName, DataSplitEnum.HOT.value());
        } else {
            hintManager.addTableShardingValue(tableName, dataSplitTagAnnotation.value());

        }
        return joinPoint.proceed();
    }

}